package classDAO;

import java.util.List;

import mappedClass.UserType;

import org.hibernate.Query;
import org.hibernate.Session;

import testhibernate.HibernateUtil;

public class UserTypeDAO implements DAO {

	public List<UserType> findAll() {
		Session s = HibernateUtil.getSessionFactory().openSession();
		List<UserType> list = s.createQuery("FROM UserType ut").list();
		s.close();
		return list;
	}

	public Object getById(int id) {
		Session s = HibernateUtil.getSessionFactory().openSession();

		return (UserType) s.get(UserType.class, id);
	}

	public int getIdByName(String name) {
		Session s = HibernateUtil.getSessionFactory().openSession();

		Query q = s.createQuery("SELECT id FROM UserType u where u.name= :name")
				.setString("name", name);
		int id = (Integer) q.uniqueResult();
		return id;
	}
	
	public boolean addUserType(int id, String name) {
		
		Session s = HibernateUtil.getSessionFactory().openSession();
		
		/** WE START THE TRANSACTION **/
		s.beginTransaction();
		
		UserType newUT = new UserType(id, name);
		s.save(newUT);
		
		/** COMMIT AND CLOSE **/
		s.getTransaction().commit();
		s.close();
		
		return true;
	}

}
